package com.example.demo.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.Result;
import com.example.demo.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@CrossOrigin  // 添加这个注解
public class UserController {
    private final UserService userService;

    /**
     * 登錄
     * @param user
     * @return
     */
    @PostMapping("/getUserById")
    public Result<Map<String, Object>> getUserById(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getUserName, user.getUserName()).eq(User::getPassworld, user.getPassworld());  // 修改为getPassword
        User one = userService.getOne(queryWrapper);
        if (BeanUtil.isEmpty(one)){
            return Result.error("账户或密码错误，请重试!");
        }
        
        // 创建包含token和用户ID的Map
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", TokenUtil.getToken(one.getUserName(), one.getPassworld()));
        resultMap.put("userId", one.getId());
        
        return Result.success(resultMap);
    }
}
